package com.coocaa.aries.core.base;

import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.coocaa.aries.core.base.entity.BaseEntity;
import com.coocaa.aries.core.base.exception.ExceptionUtil;
import com.coocaa.aries.core.base.mapper.IBaseMapper;
import com.coocaa.aries.core.base.model.BaseQueryModel;
import com.coocaa.aries.core.base.model.PageResultModel;
import com.coocaa.aries.core.base.util.PageQueryUtil;
import com.coocaa.aries.core.tool.InstanceUtil;
import com.coocaa.aries.core.tool.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author bijiahao
 * @date : 2018/9/6.
 * @description: 适用于-标准表结构的
 */
@Slf4j
public abstract class BaseBizImpl<M extends IBaseMapper<T>, T extends BaseEntity> implements IBaseBiz<T> {
    @Autowired
    private M mapper;


    @Override
    public boolean insertBatch(List<T> entityList) {
        if (CollectionUtils.isEmpty(entityList)) {
            throw new IllegalArgumentException("Error: entityList must not be empty");
        }

        try (SqlSession batchSqlSession = sqlSessionBatch()) {
            int size = entityList.size();
            int batchSize = size;
            String sqlStatement = sqlStatement(SqlMethod.INSERT_ONE);
            for (int i = 0; i < size; i++) {
                batchSqlSession.insert(sqlStatement, entityList.get(i));
                if (i >= 1 && i % batchSize == 0) {
                    batchSqlSession.flushStatements();
                }
            }
            batchSqlSession.flushStatements();
        } catch (Exception e) {
            log.error(ExceptionUtil.getErrorPrintLog("批量插入保存", e));
            throw new MybatisPlusException("Error: 批量保存异常", e);
        }
        return true;
    }


    protected String sqlStatement(SqlMethod sqlMethod) {
        return SqlHelper.table(currentModelClass()).getSqlStatement(sqlMethod.getMethod());
    }

    /**
     * 批量操作 SqlSession
     */
    protected SqlSession sqlSessionBatch() {
        return SqlHelper.sqlSessionBatch(currentModelClass());
    }

    protected Class<T> currentModelClass() {
        return ReflectionKit.getSuperClassGenericType(getClass(), 1);
    }


    /**
     * 新增
     *
     * @param entity
     * @return
     */
    @Override
    public T add(T entity) {
        entity.setFlag(1);
        Date date = DateUtil.getCurDate();
        entity.setCreatedDate(date);
        entity.setLastUpdateDate(date);
        mapper.insert(entity);
        return entity;
    }

    /**
     * 更新-通过自增ID
     *
     * @param entity
     * @return
     */
    @Override
    public T updateById(T entity) {
        Date date = DateUtil.getCurDate();
        entity.setLastUpdateDate(date);
        mapper.updateById(entity);
        return entity;
    }

    /**
     * 查询-通过自增ID
     *
     * @param id
     * @return
     */
    @Override
    public T queryById(Integer id) {
        return mapper.selectById(id);
    }

    @Override
    public PageResultModel<T> getCommonPageResult(Map params) {
        // 获取总记录数
        Integer total = getMapper().selectCountPage(params);
        List<T> resultList = InstanceUtil.newArrayList();
        if (total > 0) {
            // 获取总的数据
            resultList = getMapper().queryCommonPageList(params);
        }
        return PageResultModel.getPageResultModel(total, resultList);
    }

    @Override
    public PageResultModel<T> getCommonPageResult(BaseQueryModel model) {
        Map<String, Object> params = PageQueryUtil.getFilterMap(model);
        return getCommonPageResult(params);
    }

    public M getMapper() {
        return mapper;
    }
}
